<template>
  <div class="container">
    <div class="main-layout">
      <!-- 左侧角色展示 -->
      <aside class="role-panel">
        <h2>AI角色语音聊天</h2>
        <div class="role-select-row">
          <label class="role-select-label">切换角色：</label>
          <el-select v-model="selectedRoleIdx" placeholder="请选择角色">
            <el-option
              v-for="(role, idx) in roles"
              :key="role.name"
              :label="role.name"
              :value="idx"
            />
          </el-select>
        </div>

        <img :src="roles[selectedRoleIdx].img" class="role-img" style="margin-top: 8px;" />
        <h3 class="role-name" style="text-align: center;">{{ roles[selectedRoleIdx].name }}</h3>
        <div class="role-desc">{{ roles[selectedRoleIdx].desc }}</div>
      </aside>
      <!-- 右侧对话区 -->
      <section class="chat-panel">
        <div style="display: flex; gap: 8px;">
          <el-button type="primary" :icon="MoreFilled" style="width: 100px; margin-bottom: 8px;" @click="historyDialogVisible = true">
            历史对话
          </el-button>
          <el-button type="primary" :icon="Plus" style="width: 100px; margin-bottom: 8px;" @click="$router.push('/createRole')">
            创建角色
          </el-button>
          <el-button type="primary" :icon="ChatLineRound" style="width: 120px; margin-bottom: 8px;"   @click="clearChat">
            创建新对话
          </el-button>
        </div>

        <div class="chat-box">

          <div v-for="(msg, i) in chat" :key="i" class="chat-item">
            <strong>{{ msg.role === '用户' ? '您' : msg.role }}：</strong>
            <span>{{ msg.text }}</span>
          </div>
        </div>



        <div class="chat-actions">
          <input
            v-model="input"
            :disabled="listening"
            placeholder="请输入或使用语音"
            class="input-box"
            @keydown.enter="sendMsg"
          />
          <button @click="sendMsg" :disabled="!input || listening">发送</button>
          <button @click="startListen" :disabled="listening">
            {{ listening ? '听您说话中...' : '语音输入' }}
          </button>
        </div>

        <!-- <div>
          <button @click="startRecord" :disabled="recording">开始录音</button>
          <button @click="stopRecord" :disabled="!recording">停止识别</button>
          <button @click="playAudio" :disabled="!audioUrl">播放录音</button>

          <audio v-if="audioUrl" :src="audioUrl" controls></audio>
          <p>识别结果：{{ asrText }}</p>
        </div> -->
      </section>
    </div>
    <el-dialog
      title="历史对话记录"
      v-model="historyDialogVisible"
      width="600px"
      center
    >
      <!-- 历史对话列表 -->
      <div class="history-list">
        <!-- 无历史记录时显示提示 -->
        <div class="no-history" v-if="historyChats.length === 0">
          暂无历史对话记录~ 快去和AI角色聊天吧！
        </div>

        <!-- 有历史记录时渲染列表 -->
        <div
          class="history-item"
          v-for="history in historyChats"
          :key="history.id"
          @click="loadHistoryChat(history)" >
        >
          <!-- 角色名 + 创建时间 -->
          <div class="history-header">
            <span class="history-role">{{ history.roleName }}</span>
            <span class="history-time">{{ history.createTime }}</span>
          </div>
          <!-- 显示第一条提问（用户的问题） -->
          <div class="history-question">
            提问：{{ history.chat[0]?.text || '无内容' }}
          </div>
        </div>
      </div>

      <!-- 对话框底部关闭按钮 -->
      <template #footer>
        <el-button @click="historyDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElDialog } from 'element-plus'
import { useRolesStore } from '@/stores/roles'
import { MoreFilled, Plus, ChatLineRound } from '@element-plus/icons-vue'

const store = useRolesStore()
const roles = store.roles
const selectedRoleIdx = ref(0)


const historyChats = ref([]) // 存储所有历史对话
const historyDialogVisible = ref(false) // 控制历史对话框显示/隐藏
const chat = ref([])
const input = ref('')
const listening = ref(false)
const isNewChat = ref(false)
const currentChatId = ref(null)

// const recording = ref(false);
// const audioUrl = ref(null);
// const asrText = ref("");

// let mediaRecorder = null;
// let chunks = [];
// let mimeType = "";

// async function startRecord() {
//   const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
//   if (MediaRecorder.isTypeSupported("audio/ogg; codecs=opus")) {
//     mimeType = "audio/ogg; codecs=opus";
//   } else if (MediaRecorder.isTypeSupported("audio/webm; codecs=opus")) {
//     mimeType = "audio/webm; codecs=opus";
//   } else if (MediaRecorder.isTypeSupported("audio/mp4")) {
//     mimeType = "audio/mp4";
//   } else {
//     mimeType = ""; // 浏览器自己决定默认格式
//   }
//   console.log("Using MIME type:", mimeType);
//   mediaRecorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
//   chunks = [];

//   mediaRecorder.ondataavailable = (e) => chunks.push(e.data);
//   mediaRecorder.onstop = async () => {
//     const blob = new Blob(chunks, { type: "audio/webm" });
//     audioUrl.value = URL.createObjectURL(blob);
//     const form = new FormData();
//     form.append("audio", blob, "speech.webm");

//     const resp = await fetch("/api/asr", {
//       method: "POST",
//       body: form
//     });
//     const data = await resp.json();
//     asrText.value = data.text || "识别失败，请重试。";
//   };

//   mediaRecorder.start();
//   recording.value = true;
// }

// function stopRecord() {
//   recording.value = false;
//   mediaRecorder && mediaRecorder.stop();
// }

// function playAudio() {
//   if (audioUrl.value) {
//     const audio = new Audio(audioUrl.value);
//     audio.play();
//   }
// }

async function sendMsg() {
  if (!input.value) return
  const userMsg = { role: '用户', text: input.value }
  chat.value.push(userMsg)
  const aiText = await getAnswer(selectedRoleIdx.value, input.value)
  chat.value.push({ role: roles[selectedRoleIdx.value].name, text: aiText })
  speak(aiText)
  input.value = ''

  // 当前完整对话（深拷贝）
  const currentChat = [...chat.value]
  const currentRole = roles[selectedRoleIdx.value]

  // 情况1：新对话（刚点击“创建新对话”后首次发送消息）
  if (isNewChat.value) {
    // 生成新的历史记录，绑定当前对话ID
    const newHistory = {
      id: currentChatId.value, // 用当前对话ID作为历史记录ID
      roleIdx: selectedRoleIdx.value,
      roleName: currentRole.name,
      chat: currentChat,
      createTime: new Date().toLocaleString(),
      updateTime: new Date().toLocaleString() // 新增：记录最后更新时间
    };
    historyChats.value.push(newHistory);
    isNewChat.value = false; // 切换为非新对话
  }
  // 情况2：同一对话续聊（找到对应的历史记录更新）
  else {
    // 找到当前对话ID对应的历史记录
    const targetHistory = historyChats.value.find(
      item => item.id === currentChatId.value
    );

    if (targetHistory) {
      // 更新完整对话内容
      targetHistory.chat = currentChat;
      // 更新最后修改时间（方便查看对话是否有新内容）
      targetHistory.updateTime = new Date().toLocaleString();
    }
    // 边界情况：首次对话（未点击“创建新对话”直接发送）
    else {
      currentChatId.value = Date.now(); // 生成新ID
      historyChats.value.push({
        id: currentChatId.value,
        roleIdx: selectedRoleIdx.value,
        roleName: currentRole.name,
        chat: currentChat,
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString()
      });
    }
  }
}

// 清空对话记录（新建对话功能）
function clearChat() {
  chat.value = []; // 清空当前对话
  input.value = '';
  window.speechSynthesis.cancel();
  isNewChat.value = true; // 标记为新对话
  // 关键：生成新的对话ID（时间戳确保唯一）
  currentChatId.value = Date.now();
}

function loadHistoryChat(historyItem) {
  selectedRoleIdx.value = historyItem.roleIdx;
  chat.value = [...historyItem.chat]; // 加载完整对话
  // 关键：同步当前对话ID为历史记录的ID
  currentChatId.value = historyItem.id;
  isNewChat.value = false; // 标记为非新对话（续聊状态）
  historyDialogVisible.value = false;
}

// 后端API (示例：真实需接入 LLM接口)
async function getAnswer(roleIdx, text) {
  const prompt = roles[roleIdx].prompt(text)
  // 可替换为真实 API 调用
  try {
    const resp = await fetch('/api/ai', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ prompt }),
    })
    const data = await resp.json()
    return data.answer || '暂时无法生成答案。'
  } catch {
    // mock fallback
    if (roleIdx === 0) return `魔法棒闪耀光芒！勇敢面对：“${text}”吧！`
    else if (roleIdx === 1) return `那么，你真的理解了“${text}”的本质么？`
    else return `侦探的线索是：“${text}”。你能发现隐藏的真相吗？`
  }
}

// TTS语音合成
function speak(text) {
  if (!window.speechSynthesis) return;

  // 创建一个语音合成对象
  const utter = new window.SpeechSynthesisUtterance(text);

  // 设置语速
  utter.rate = roles[selectedRoleIdx.value].name === '苏格拉底' ? 1.1 : 1;

  // 获取浏览器支持的语音列表
  const voices = window.speechSynthesis.getVoices();

  // 查找包含情感元素的语音
  let selectedVoice = voices.find(voice => voice.name.toLowerCase().includes('happy') || voice.name.toLowerCase().includes('excited'));

  if (!selectedVoice) {
    // 如果没有找到情感化的语音，可以选择中文语音
    selectedVoice = voices.find(voice => voice.lang === 'zh-CN'); // 选择中文语音
  }

  // 设置选择的语音
  utter.voice = selectedVoice;

  // 设置音调，根据角色调整音调来模拟更多的情感
  utter.pitch = roles[selectedRoleIdx.value].name === '苏格拉底' ? 1.5 : 1.2; // 可以根据角色调整音调
  // 提高音调可以使语音更有表现力（例如，表达高兴）

  // 设置音量
  utter.volume = 1; // 音量最大

  // 调整语速和情感表现（通过 rate 和 pitch）
  if (roles[selectedRoleIdx.value].name === '苏格拉底') {
    utter.rate = 1.1; // 设置稍快的语速
  } else if (roles[selectedRoleIdx.value].name === '愉快的角色') {
    utter.rate = 1.2; // 语速较快，表示兴奋或愉快
    utter.pitch = 1.4; // 音调稍高，表达愉快的情感
  } else if (roles[selectedRoleIdx.value].name === '悲伤的角色') {
    utter.rate = 0.9; // 语速稍慢，表达悲伤
    utter.pitch = 0.8; // 音调低一些，表现出悲伤的情感
  }

  // 启动语音合成
  window.speechSynthesis.speak(utter);
}
</script>

<style scoped>
.container {
  min-width: 100vh;
  min-height: 100vh;
  margin: 0 auto;
  font-family: sans-serif;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  background-image: url('/bg_shouye.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  background-attachment: fixed;
}

/* 主内容左右分栏 */
.main-layout {
  display: flex;
  width: 100%;
  min-height: 600px;
  box-shadow: 0 4px 18px #c7daea33;
  border-radius: 16px;
  overflow: hidden;
}

/* 角色区样式 */
.role-panel {
  width: 450px;
  min-width: 200px;
  height: 850px;
  background: #e9f0fa;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 32px 12px 12px 12px;
  margin-top: 16px;
  box-sizing: border-box;
  border-radius: 12px;
  border-right: 1px solid #d6e6f5;
  margin-left: 12px;
}

.role-img {
  width: 400px;
  height: 600px;
  border-radius: 12px;
  object-fit: cover;
  border: 2px solid #ccdaf6;
  margin-bottom: 18px;
  background: #fff;
}

.role-name {
  font-size: 20px;
  margin-bottom: 5px;
  margin-top: 0;
}

.role-desc {
  color: #555;
  font-size: 15px;
  margin-bottom: 18px;
  text-align: center;
}

.role-select-label {
  width: 160px;
  margin-bottom: 4px;
  margin-top: 8px;
}

.role-select {
  width: 160px;
  padding: 5px;
}

/* 聊天气泡区 */
.chat-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 32px 24px 14px 24px;
  min-width: 0;
}

h2 {
  margin-top: 0;
  margin-left: 8px;
  margin-bottom: 14px;
}

.chat-box {
  flex: 1;
  max-height: 720px;
  overflow: auto;
  background: rgba(0, 0, 0, 0.3);  /* 黑色 + 60%透明度 */
  color: #fff;                     /* 白色文字，确保对比度高 */
  border-radius: 10px;             /* 可选：圆角美化 */
  padding: 10px;
  margin-bottom: 18px;
}
.chat-item {
  margin-bottom: 7px;
}

.chat-actions {
  display: flex;
  gap: 8px;
  margin-top: 10px;
}

.input-box {
  flex: 1;
  min-width: 0;
  padding: 8px;
  border-radius: 5px;
  border: 1px solid #d8d8d8;
}

button {
  padding: 0 16px;
  line-height: 34px;
  border-radius: 5px;
  border: none;
  background: #207cd6;
  color: #fff;
  cursor: pointer;
  font-size: 15px;
}
button:disabled {
  background: #a0c8ea;
}

/* 响应式 手机端上下布局 */
@media (max-width: 700px) {
  .main-layout {
    flex-direction: column;
    min-height: 0;
    box-shadow: none;
    border-radius: 0;
  }
  .role-panel {
    flex-direction: row;
    width: 100%;
    min-width: 0;
    border-right: none;
    border-bottom: 1px solid #dde9f9;
    justify-content: flex-start;
  }
  .role-img {
    margin-bottom: 0;
    margin-right: 16px;
  }
  .chat-panel {
    padding: 16px 8px 10px 8px;
  }
}

.role-select-row {
  display: flex;
  align-items: center;
  margin-left: 8px;
  gap: 8px; /* 控制间距 */
}
.history-list {
  max-height: 400px; /* 限制列表高度，超出滚动 */
  overflow-y: auto;
  padding: 10px 0;
}

.history-item {
  padding: 12px 16px;
  border-radius: 8px;
  background: #f5f7fa;
  margin-bottom: 8px;
  cursor: pointer;
  transition: background 0.3s ease;
}

/* 鼠标悬浮时高亮 */
.history-item:hover {
  background: #e9f0fa;
  border-left: 3px solid #207cd6;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
  font-size: 14px;
}

.history-role {
  font-weight: bold;
  color: #207cd6; /* 角色名蓝色高亮 */
}

.history-time {
  color: #999;
  font-size: 12px; /* 时间灰色小号 */
}

.history-question {
  color: #333;
  font-size: 14px;
  /* 问题过长时截断（避免换行） */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.no-history {
  text-align: center;
  color: #999;
  padding: 30px 0;
  font-size: 14px;
}
</style>
